<script setup name="View2d">
import { ref, onMounted, onActivated, computed, watch, reactive } from "vue";
import { useRoute } from "vue-router";
import StudyBar from "../components/StudyBar.vue";
import SeriesBar from "../components/SeriesBar.vue";
import DisplayerArea from "../components/DisplayerArea.vue";
// import SystemInfo from "../components/SystemInfo.vue";
import { useArchiveStore } from "../stores/archive";
import { useAppStore } from "../stores/appStore";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import MainToolbar from "../components/MainToolbar.vue";
import { enableReferenceLines } from "../cornerstone3D/initTools";

const router = useRouter();

const archiveStore = useArchiveStore();
const { seriesList } = storeToRefs(archiveStore);

const appStore = useAppStore();
const route = useRoute();
const view2d = ref(null);
const navDisplay = ref(null);
const studyBar = ref(null);
const seriesBar = ref(null);
const displayArea = ref(null);

// const systemInfo = ref(null);
// const toolbar = ref(null);

const navbarHW = ref(146);
const toolbarHW = ref(420);

const wmFont = reactive({
	color: "rgba(0, 0, 0, .15)"
});

const { toolbarPos, navbarPos } = storeToRefs(appStore);

const mainClass = computed(() => {
	const vorh = toolbarPos.value === "top" ? "vertical" : "horizontal-reverse";
	return "flex-" + vorh;
});

const navDisplayClass = computed(() => {
	const vorh = navbarPos.value === "bottom" ? "vertical-reverse" : "horizontal";
	return "flex-" + vorh;
});

const navResizerClass = computed(() => {
	const vorh = navbarPos.value === "bottom" ? "horizontal" : "vertical";
	return "resizer-" + vorh;
});

const navClass = computed(() => {
	return "nav-" + navbarPos.value;
});

const navbarStyle = computed(() => {
	if (navbarPos.value === "bottom") {
		return {
			height: navbarHW.value + "px"
		};
	} else {
		return {
			width: navbarHW.value + "px"
		};
	}
});

watch(toolbarHW, (n, o) => {
	// console.log("toolbarHW changed:", n, o);
	let navDispWidth;
	if (n > o) navDispWidth = navDisplay.value.clientWidth - 2;
	else navDispWidth = navDisplay.value.clientWidth - 1;
	seriesBar.value.setWidth(navDispWidth);
	displayArea.value.setWidth(navDispWidth);
});

watch(
	() => seriesList.value.length,
	(n, o) => {
		// console.log("seriesList changed:", n);
		displayArea.value.displayAuto();
	}
);

function resizeNavbar(e) {
	e.stopPropagation();
	// console.log("resizeNavbar", e.target);
	view2d.value.style.cursor = navbarPos.value === "bottom" ? "ns-resize" : "ew-resize";
	view2d.value.onmousemove = function (e) {
		// console.log("onmousemove", e.movementX, e.movementY);
		let delta, minVal, maxVal;
		if (navbarPos.value === "bottom") {
			delta = -e.movementY;
			minVal = 110;
			maxVal = 165;
		} else {
			delta = e.movementX;
			minVal = 146;
			maxVal = 220;
		}

		// let delta = navbarPos.value === "bottom" ? -e.movementY : e.movementX;
		const value = navbarHW.value + delta;

		if (value < minVal || value > maxVal) return;
		navbarHW.value = value;
		// console.log("navbarHW:", navbarHW.value);
	};

	document.onmouseup = function () {
		// console.log("mouseup");
		view2d.value.onmousemove = null;
		document.onmouseup = null;
		view2d.value.style.cursor = "";
	};
}

const toggleNavbarPos = () => {
	navbarPos.value = navbarPos.value === "bottom" ? "left" : "bottom";
	navbarHW.value = navbarPos.value === "bottom" ? 120 : 146;
	if (navbarPos.value === "bottom") {
		seriesBar.value.setWidth(navDisplay.value.clientWidth);
	}
	// console.log("toggleNavbarPos navbarPos:", navbarPos.value);
	// console.log("toggleNavbarPos appStore.navbarPos:", appStore.navbarPos);
};

const toggleToolbarPos = () => {
	toolbarPos.value = toolbarPos.value === "top" ? "right" : "top";
	toolbarHW.value = toolbarPos.value === "top" ? 146 : 220;
};

async function OnToolbarAction(action) {
	// console.log("OnToolbarAction", action);

	switch (action.name) {
		case "changeToolbarPos":
			toggleToolbarPos();
			break;
		case "changeNavPos":
			toggleNavbarPos();
			break;
		case "openFolder":
			{
				const fileHandles = await openFolder();
				// const dcmfiles = fileHandles.filter(file => file.name.endsWith(".dcm"));
				// console.log("openFolder, fileHandles:", fileHandles);
				if (Array.isArray(fileHandles)) {
					fileHandles.forEach(fileHandle => {
						// const file = await fileHandle.getFile();
						// await archiveStore.archiveFile(file);
						fileHandle.getFile().then(file => {
							archiveStore.archiveFile(file);
						});
					});
				} else {
					// console.error("openFolder, fileHandles is not an array");
				}
			}

			break;
		case "openPacs":
			displayArea.value.showPacsWnd();
			break;
		case "openFile":
			{
				const file = action.files[0];
				archiveStore.archiveFile(file);
			}
			break;
		case "layout":
			displayArea.value.setLayout(action.row, action.col);
			break;
		case "displayAuto":
			displayArea.value.displayAuto();
			break;
		case "clearDisplay":
			displayArea.value.clear();
			break;
		case "deleteViewerMeasure":
			displayArea.value.removeSelectedViewportMeasures();
			break;
		case "flipH":
		case "flipV":
		case "invert":
		case "rotate":
			displayArea.value.setViewportProperties(action);
			break;
		case "colorMap":
			displayArea.value.setViewportColorMap(action.value);
			break;
		case "resetCamera":
			displayArea.value.resetViewportCamera();
			break;
		case "setWindow":
			displayArea.value.setViewportWindow(action.wl, action.ww);
			break;
		case "dcmtag":
			displayArea.value.showDcmTagsDialog();
			break;
		case "crossline":
			enableReferenceLines(action.checked);
			break;
		case "mprvr":
			show3dView();
			break;
		default:
			break;
	}
}

function show3dView() {
	const imageIds = appStore.currentDisplayer.getImageIds();
	// console.log("show3dView:", imageIds);

	if (imageIds.length > 9) {
		router.push({
			path: "dicom3d"
		});
	} else {
		ElMessage.warning("图像数量过少，无法显示3D视图...");
	}
}

async function openFolder() {
	try {
		// 请求用户选择一个文件夹
		const handle = await showDirectoryPicker();
		const fileHandles = [];
		await processHandle(handle, fileHandles);
		// console.log("handle2:", fileHandles);
		return fileHandles;
	} catch (err) {
		// console.error("无法打开文件夹", err);
		return null;
	}
}

async function processHandle(handle, fileHandles) {
	if (handle.kind === "file") {
		return;
	}
	const itr = await handle.entries();
	for await (const entry of itr) {
		// console.log("entry:", entry);
		if (entry[1].kind === "file" && entry[1].name.toLowerCase().endsWith(".dcm")) {
			fileHandles.push(entry[1]);
		} else {
			await processHandle(entry[1], fileHandles);
		}
	}
}

onMounted(() => {
	// console.log("Home mounted, studyId:", route.params.studyId);
	console.log("View2d mounted, studyId:", route.query.studyId);
	if (route.query.studyId) {
		let pacsurl;
		if (config.pacs.hoFormat) {
			let params = "studyid=" + route.query.studyId;
			params += "&timestamp=" + new Date().getTime();
			// console.log(params);
			pacsurl = config.pacs.imageapi + "?params=" + ParamEncode(params);
		} else {
			pacsurl = config.pacs.imageapi + "/" + route.query.studyId;
		}

		console.log("View2d mounted, pacsurl:", pacsurl);

		fetch(pacsurl)
			.then(response => response.json())
			.then(data => {
				// console.log("View2d mounted, data:", data);
				data.forEach(image => {
					const dcm = "dicomweb:" + image;
					archiveStore.archiveFile(dcm);
				});
			})
			.catch(error => {
				console.error("View2d mounted, error:", error);
			});
	}
});

onActivated(() => {
	console.log("View2d activated");
	setTimeout(() => {
		displayArea.value.displayAuto();
	}, 300);
});
</script>

<template>
	<el-watermark :font="wmFont" :content="['西哥写代码']">
		<div class="container flex-vertical" ref="view2d" @contextmenu.prevent>
			<div class="head-menubar">
				<MainToolbar ref="mainToolbar" @action="OnToolbarAction" />
			</div>
			<div class="header flex-horizontal">
				<!-- <div class="logo">
					<SystemInfo ref="systemInfo" />
				</div> -->
				<div class="study-list">
					<!-- Study List -->
					<StudyBar ref="studyBar" />
				</div>
			</div>
			<div class="main" :class="mainClass">
				<div class="nav-display" :class="navDisplayClass" ref="navDisplay">
					<div :class="navClass" :style="navbarStyle">
						<SeriesBar ref="seriesBar" />
					</div>
					<div :class="navResizerClass" @mousedown="resizeNavbar"></div>
					<div class="display-area">
						<DisplayerArea ref="displayArea" />
					</div>
				</div>
			</div>
			<div class="footer">Statusbar</div>
		</div>
	</el-watermark>
</template>

<style scoped lang="scss">
$bg-color: #333;
$main-color: lightblue;
$header-color: #45b7ec;
$footer-color: #45b7ec;
$resizer-width: 2px;
$header-height: 100px;
$footer-height: 34px;

.container {
	background-color: var(--color-theme-bg);
	height: 100vh;
	width: 100vw;
	max-width: 100%;
	max-height: 100%;
	justify-content: center;
	color: var(--color-theme-text);
	user-select: none;
	overflow: auto;
}

.flex-vertical {
	display: flex;
	flex-direction: column;
}

.flex-vertical-reverse {
	display: flex;
	flex-direction: column-reverse;
}

.flex-horizontal {
	display: flex;
	flex-direction: row;
}

.flex-horizontal-reverse {
	display: flex;
	flex-direction: row-reverse;
}

.resizer-vertical {
	cursor: ew-resize;
	width: $resizer-width;
	background-color: gray;
	flex-shrink: 0;
	z-index: 10;
}

.resizer-horizontal {
	cursor: ns-resize;
	height: $resizer-width;
	background-color: gray;
	width: 100%;
	flex-shrink: 0;
	z-index: 10;
}

.header {
	height: $header-height;
	border-bottom: gray solid 1px;

	.logo {
		height: 100%;
		width: 200px;
		border-right: gray solid 1px;
		flex-shrink: 0;
	}

	.study-list {
		flex: 1;
		height: 100%;
	}
}

.main {
	width: 100%;
	flex: 1;

	.nav-display {
		flex: 1;
	}

	.toolbar-top {
		height: 200px;
		width: 100%;
	}

	.toolbar-right {
		width: 200px;
		height: 100%;
		flex-shrink: 0;
	}

	.nav-display {
		.display-area {
			flex: 1;
			flex-shrink: 0;
		}
		.nav-left {
			height: 100%;
		}

		.nav-bottom {
			width: 100%;
		}
	}
}

.footer {
	height: $footer-height;
	border-top: gray solid 1px;
}
</style>
